<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of FilterActions
 *
 * @author jhonny
 */
class FilterActions extends sfActions{
    public function executeBuscarPais(sfWebRequest $request) {
//      return parent::execute_ajax($request);
    }

    public function executeFindRegionesByPaisBusqueda(sfWebRequest $request) {
//      $respuesta='"Regiones":[{"Nombre":"Capital Federal","Id":1,"ShowMatchedRegions":true},{"Nombre":"G.B.A. Zona Norte","Id":2,"ShowMatchedRegions":true},{"Nombre":"G.B.A. Zona Oeste","Id":3,"ShowMatchedRegions":true},{"Nombre":"G.B.A. Zona Sur","Id":4,"ShowMatchedRegions":true},{"Nombre":"Costa Atlantica","Id":5,"ShowMatchedRegions":true},{"Nombre":"Interior Buenos Aires","Id":6,"ShowMatchedRegions":true},{"Nombre":"Catamarca","Id":8,"ShowMatchedRegions":true},{"Nombre":"Chaco","Id":9,"ShowMatchedRegions":true},{"Nombre":"Chubut","Id":10,"ShowMatchedRegions":true},{"Nombre":"Cordoba","Id":11,"ShowMatchedRegions":true},{"Nombre":"Corrientes","Id":12,"ShowMatchedRegions":true},{"Nombre":"Entre Rios","Id":13,"ShowMatchedRegions":true},{"Nombre":"Formosa","Id":14,"ShowMatchedRegions":true},{"Nombre":"Jujuy","Id":15,"ShowMatchedRegions":true},{"Nombre":"La Pampa","Id":16,"ShowMatchedRegions":true},{"Nombre":"La Rioja","Id":17,"ShowMatchedRegions":true},{"Nombre":"Mendoza","Id":18,"ShowMatchedRegions":true},{"Nombre":"Misiones","Id":19,"ShowMatchedRegions":true},{"Nombre":"Neuquen","Id":20,"ShowMatchedRegions":true},{"Nombre":"Rio Negro","Id":22,"ShowMatchedRegions":true},{"Nombre":"Salta","Id":23,"ShowMatchedRegions":true},{"Nombre":"San Juan","Id":24,"ShowMatchedRegions":true},{"Nombre":"San Luis","Id":25,"ShowMatchedRegions":true},{"Nombre":"Santa Cruz","Id":26,"ShowMatchedRegions":true},{"Nombre":"Santa Fe","Id":27,"ShowMatchedRegions":true},{"Nombre":"Santiago Del Estero","Id":28,"ShowMatchedRegions":true},{"Nombre":"Tierra Del Fuego","Id":29,"ShowMatchedRegions":true},{"Nombre":"Tucuman","Id":30,"ShowMatchedRegions":true}]';
//      $respuesta =  array("Regiones"=>array(array("Nombre"=>"Capital Federal","Id"=>'1',"ShowMatchedRegions"=>'true'),array("Nombre"=>"G.B.A. Zona Norte","Id"=>'2',"ShowMatchedRegions"=>'true')));
//      $this->getResponse()->setContent($respuesta);
////     $this->form->widgetSchema['barrio_id']->setAttribute('disabled', 'disabled');
//    $paisId = $request->getParameter('idPais');
        $this->forwardUnless($idPais = $request->getParameter('idPais'), 'homes', 'FindRegionesByPaisBusqueda');
        if ($request->isXmlHttpRequest()) {
            $this->logMessage('is isXmlHttpRequest ', "info");
        } else {
            //$this->forward404Unless(null);
        }
        $this->logMessage("parameter idPais $idPais ", "info");
        $this->regiones = Doctrine_Core::getTable('Provincia')->getProvincias($idPais);
        $this->forward404Unless($this->regiones);
        $this->logMessage($this->regiones, "info");
        $respuesta = $this->convertRegiones($this->regiones);
        return $this->renderText(json_encode($respuesta));
    }

    public function convertRegiones($regiones) {
        $result = array();

        foreach ($regiones as $value) {
            $item = array("Nombre" => $value->getName(), "Id" => $value->getId(), "ShowMatchedRegions" => 'true');
            array_push($result, $item);
        }
        $respuesta = array("Regiones" => $result);
        return $respuesta;
    }

    public function executeFindChildrenByRegionBusqueda(sfWebRequest $request) {
//      $respuesta='"Regiones":[{"Nombre":"Capital Federal","Id":1,"ShowMatchedRegions":true},{"Nombre":"G.B.A. Zona Norte","Id":2,"ShowMatchedRegions":true},{"Nombre":"G.B.A. Zona Oeste","Id":3,"ShowMatchedRegions":true},{"Nombre":"G.B.A. Zona Sur","Id":4,"ShowMatchedRegions":true},{"Nombre":"Costa Atlantica","Id":5,"ShowMatchedRegions":true},{"Nombre":"Interior Buenos Aires","Id":6,"ShowMatchedRegions":true},{"Nombre":"Catamarca","Id":8,"ShowMatchedRegions":true},{"Nombre":"Chaco","Id":9,"ShowMatchedRegions":true},{"Nombre":"Chubut","Id":10,"ShowMatchedRegions":true},{"Nombre":"Cordoba","Id":11,"ShowMatchedRegions":true},{"Nombre":"Corrientes","Id":12,"ShowMatchedRegions":true},{"Nombre":"Entre Rios","Id":13,"ShowMatchedRegions":true},{"Nombre":"Formosa","Id":14,"ShowMatchedRegions":true},{"Nombre":"Jujuy","Id":15,"ShowMatchedRegions":true},{"Nombre":"La Pampa","Id":16,"ShowMatchedRegions":true},{"Nombre":"La Rioja","Id":17,"ShowMatchedRegions":true},{"Nombre":"Mendoza","Id":18,"ShowMatchedRegions":true},{"Nombre":"Misiones","Id":19,"ShowMatchedRegions":true},{"Nombre":"Neuquen","Id":20,"ShowMatchedRegions":true},{"Nombre":"Rio Negro","Id":22,"ShowMatchedRegions":true},{"Nombre":"Salta","Id":23,"ShowMatchedRegions":true},{"Nombre":"San Juan","Id":24,"ShowMatchedRegions":true},{"Nombre":"San Luis","Id":25,"ShowMatchedRegions":true},{"Nombre":"Santa Cruz","Id":26,"ShowMatchedRegions":true},{"Nombre":"Santa Fe","Id":27,"ShowMatchedRegions":true},{"Nombre":"Santiago Del Estero","Id":28,"ShowMatchedRegions":true},{"Nombre":"Tierra Del Fuego","Id":29,"ShowMatchedRegions":true},{"Nombre":"Tucuman","Id":30,"ShowMatchedRegions":true}]';
        $pais = "";
        $provincia ="";
        $respuesta = array("Barrios" => array(array("Nombre" => "Abasto", "Id" => '1', "SubBarrios" => array()), array("Nombre" => "Agronomia", "Id" => '42', "SubBarrios" => array()), array("Nombre" => "Almagro", "Id" => '2', "SubBarrios" => array(array("Nombre" => "Almagro Norte", "Id" => "1"), array("Nombre" => "Almagro Sur", "Id" => "2"))), array("Nombre" => "Balvanera", "Id" => '44', "SubBarrios" => array()), array("Nombre" => "Barracas", "Id" => '3', "SubBarrios" => array())));
        $idRegionBusqueda = $request->getParameter('idRegionBusqueda');
        $this->logMessage("parameter idRegionBusqueda $idRegionBusqueda ", "info");
        $this->forward404Unless($idRegionBusqueda);
        if ($request->isXmlHttpRequest()) {
            $this->logMessage('is isXmlHttpRequest ', "info");
        } else {
            //$this->forward404Unless(null);
        }
        $pais = Doctrine_Core::getTable('Provincia')->getPais($idRegionBusqueda);
        $provincia = Doctrine_Core::getTable('Provincia')->getProvinciaName($idRegionBusqueda);
        $this->logMessage("nombre del pais $pais nombre de la provincia $provincia " ,"info");
        if ($pais!="Argentina" || $provincia== "Capital Federal" || $provincia== "Costa Atlantica") {//capital federal
            $this->logMessage("Caso especial obtengo la info de partidos y despues de localidad" ,"info");
            $this->results = Doctrine_Core::getTable('Partido')->getCapitalFederal($idRegionBusqueda);
            $this->forward404Unless($this->results);            
            $this->results = Doctrine_Core::getTable('Localidad')->getLocalidades($this->results[0]->getId());
            $this->forward404Unless($this->results);
            $this->logMessage($this->results, "info");
            $respuesta = $this->convertCapitalFederal($this->results);
        } else {
            //Partido
            $this->logMessage("Caso normal obtengo la informacion de partidos " ,"info");
            $this->partidos = Doctrine_Core::getTable('Partido')->getPartidos($idRegionBusqueda);
            $this->forward404Unless($this->partidos);
            $this->logMessage($this->partidos, "info");
            $respuesta = $this->convertPartidos($this->partidos);
        }

        return $this->renderText(json_encode($respuesta));
    }

    public function convertCapitalFederal($results) {
        $result = array();
        $subBarrios = null;
        foreach ($results as $value) {
            $subBarrios= $this->getSubBarrios($value->getId());
            $this->logMessage("SUB-BARRIOS: $subBarrios", "info");
            $item = array("Nombre" => $value->getName(), "Id" => $value->getId(),"SubBarrios"=>$subBarrios);
//            $subBarrios= $this->getSubBarrios($value->getId());
//            array_push($item, $subBarrios);
            array_push($result, $item);
        }
        $respuesta = array("Barrios" => $result);
        return $respuesta;
    }

    public function convertPartidos($partidos) {
        $result = array();

        foreach ($partidos as $value) {
            $item = array("Nombre" => $value->getName(), "Id" => $value->getId());
            array_push($result, $item);
        }
        $respuesta = array("Partidos" => $result);
        return $respuesta;
    }

    public function executeFindLocalidadesDto(sfWebRequest $request) {
        $this->forwardUnless($idPartido = $request->getParameter('idPartido'), 'homes', 'FindLocalidadesDto');
        if ($request->isXmlHttpRequest()) {
            $this->logMessage('is isXmlHttpRequest ', "info");
        } else {
            //$this->forward404Unless(null);
        }
        $this->logMessage("parameter idPartido $idPartido ", "info");
        $localidades = Doctrine_Core::getTable('Localidad')->getLocalidades($idPartido);
        $this->forward404Unless($localidades);
        $this->logMessage($localidades, "info");
        $respuesta = $this->convertLocalidades($localidades);
        return $this->renderText(json_encode($respuesta));
    }

    public function convertLocalidades($localidades) {
        $result = array();
        $subBarrios = null;
        foreach ($localidades as $value) {
            $subBarrios= $this->getSubBarrios($value->getId());
            $item = array("Nombre" => $value->getName(), "Id" => $value->getId(),"Barrios"=>$subBarrios);
//            $subBarrios= $this->getSubBarrios($value->getId());
//            array_push($item, $subBarrios);
            array_push($result, $item);
        }
        $respuesta = array("Localidades" => $result);
        return $respuesta;
    }
    public function getSubBarrios($idLocalidad) {
       
     
       $respuesta = array();
        $barrios = Doctrine_Core::getTable('Barrio')->getBarrios($idLocalidad);
       // $this->forward404Unless($barrios);
        $this->logMessage($barrios, "info");
        

        foreach ($barrios as $value) {
             $itemSubBarrios = array("Nombre" => $value->getName(), "Id" => $value->getId());
            array_push($respuesta, $itemSubBarrios);
        }
        //$respuesta = array("Barrios" => $result);
        
        $this->logMessage("respuesta : $respuesta", "info");
//        $respuesta = $this->convertLocalidades($localidades);
       return $respuesta;
    }
    public function executeBuscarRegionesPorPais(sfWebRequest $request) {
//      return parent::execute_ajax($request);
    }

    public function executeBuscarChildrenByRegion(sfWebRequest $request) {
        $sourceClass = $request->getParameter('_ds_source_class');
        $this->logMessage($sourceClass, "info");
//         
        $ds_source_params = array("table_method" => "", "model" => "Partido", "method" => "__toString", "value_method" => "getId", "ref_method" => "getProvinciaId", "order_by" => array("name", "asc"));
        $source = new $sourceClass($ds_source_params);
        $this->logMessage($request->getParameter('_ds_source_params'), "info");
        if ('true' == $request->getParameter('_ds_get_ref_value')) {

            if (method_exists($this, sprintf('getRefValueFor%s', $request->getParameter('_ds_id')))) {
                $data = $this->$method($request, $source);
            } else {
                $data = $source->getRefValue($request->getParameter('_ds_ref'));
            }
        } else {

            if (method_exists($this, sprintf('getValuesFor%s', $request->getParameter('_ds_id')))) {
                $data = $this->$method($request, $source);
            } else {
                $data = $source->getValues($request->getParameter('_ds_ref'));
            }
        }
        $datoOutput = "";
        foreach ($data as $key => $value) {
            $this->logMessage($key, "info");
            $this->logMessage($value, "info");
//            $datoOutput+='key:'.$key.'= value:'.$value.'\n';
        }
        $this->logMessage($data, "info");
        //return $this->renderText(json_encode($data));
        $respuesta = '
            <div class="clearfix">
                <label for="institucion_partido_id">Partido</label>
                    <select name="institucion[partido_id]" id="institucion_partido_id" onclik="buscarOtroItem(this)">';
        foreach ($data as $key => $value) {
            $respuesta.='
                        <option value="' . $key . '">' . $value . '</option>';
        }
        $respuesta.='
                    </select>
            </div>';
//                   <script type="text/javascript">var ds_institucion_partido_id = new SelectDependiente({"id":"institucion_partido_id","opciones":[],"vacio":"Select partido","ajax":true,"url":"\/frontend_dev.php\/home\/buscarChildrenByRegion","cache":true,"dependiente":"","varref":"_ds_ref","varsoloref":"_ds_get_ref_value","params":{"_ds_id":"institucion_partido_id","_ds_source_class":"sfDependentSelectDoctrineSource","_ds_source_params":{"table_method":"","model":"Partido","method":"__toString","value_method":"getId","ref_method":"","order_by":""}}}).buscarOtroItem();</script>
//       $this->getResponse()->setContent($respuesta);
//       return sfView::NONE;
        $this->logMessage($respuesta, "info");
        return $this->renderText(json_encode($respuesta));
//      return parent::execute_ajax($request);
    }
}

?>
